import cgi
import os

os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
use_library('django', '1.1')

from django.utils import simplejson

from google.appengine.ext import webapp

from google.appengine.api import users
from models.root_models import rcAdmin

class AuthHandler(webapp.RequestHandler):
  def get(self, mode):
    if mode == 'check': #
      
      # Build up some defaults for unauthenticated users.
      loginStatus = {}
      loginStatus['loggedIn'] = False
      loginStatus['isAdmin'] = False
      loginStatus['name'] = ""
      
      # Check of the user is logged in.
      user = users.get_current_user()
      if user:
        loginStatus['loggedIn'] = True
        loginStatus['name'] = user.email()
          
        # Check of the user is an admin
        if users.is_current_user_admin():
          recUser = rcAdmin.get_or_insert(key_name=user.nickname(), userAcct=user, userChar=user.nickname())
          loginStatus['isAdmin'] = True
          loginStatus['name'] = recUser.userChar
      
      # Dump the object to the response
      self.response.headers['content-type'] = "text/plain"
      self.response.out.write(simplejson.dumps(loginStatus))
    
    elif mode == 'login':
      referer = self.request.get('referer', '')
      
      if(referer == ""):
        self.redirect( users.create_login_url("") )
      else:
        self.redirect( users.create_login_url( "/apis/referer%s" % self.request.get("referer", "") ) )
    
    elif mode == 'logout':
      self.redirect( users.create_logout_url("/apis/auth/check") )